//
//  HxChatManage.m
//  Runner
//
//  Created by 123456 on 2023/10/30.
//

#import "HxChatManage.h"
#import "MessageManage.h"


@implementation HxChatManage


static HxChatManage *_sharedInstance;

- (void)dealloc {
    [[HDClient sharedClient].chatManager removeDelegate:self];
}


+ (instancetype)shared {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[HxChatManage alloc] init];
    });
    return _sharedInstance;
}

- (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:@"cpd_easemob_cec_event" binaryMessenger:[registrar messenger]];
    [eventChannel setStreamHandler:self];
}

#pragma mark - FlutterStreamHandler

- (FlutterError *_Nullable)onListenWithArguments:(id _Nullable)arguments eventSink:(nonnull FlutterEventSink)events {
    self.eventSink = events;
    return nil;
}

- (FlutterError *_Nullable)onCancelWithArguments:(id _Nullable)arguments {
    self.eventSink = nil;
    return nil;
}


- (void)setEventMessage {
    [[HDClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
}

- (void)messagesDidReceive:(NSArray *)aMessages {
    if (self.eventSink) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:[MessageManage messagesToListMapWithMessages:aMessages] forKey:@"onMessage"];
        self.eventSink(dict);
    }
}

- (void)cmdMessagesDidReceive:(NSArray *)aCmdMessages {
    if (self.eventSink) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:[MessageManage messagesToListMapWithMessages:aCmdMessages] forKey:@"onCmdMessage"];
        self.eventSink(dict);
    }
}

- (void)messageStatusDidChange:(HDMessage *)aMessage error:(HDError *)aError {
    if (self.eventSink) {
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        NSMutableArray *msgs = [[NSMutableArray alloc]initWithObjects:aMessage, nil];
        [dict setObject:[MessageManage messagesToListMapWithMessages:msgs] forKey:@"onMessageStatusUpdate"];
        self.eventSink(dict);
    }
}



@end
